package vn.edu.ptithcm.pim.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Project;
import vn.edu.ptithcm.pim.dom.Resource;
import vn.edu.ptithcm.pim.dom.User;
import vn.edu.ptithcm.pim.service.ProjectService;
import vn.edu.ptithcm.pim.service.ResourceCategoryService;
import vn.edu.ptithcm.pim.service.ResourceService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.DocumentUtil;
import vn.edu.ptithcm.pim.util.FileUtil;
import vn.edu.ptithcm.pim.util.ParamUtil;

@SuppressWarnings("deprecation")
public class HandleDocumentController extends SimpleFormController {

	private ResourceService resourceService;
	private UserService userService;
	private ProjectService projectService;
	private ResourceCategoryService resourceCategoryService;

	Logger log = Logger.getLogger(HandleDocumentController.class);

	public HandleDocumentController() {
		super();
		setSessionForm(true);
		setCommandName("resource");
		setCommandClass(Resource.class);
		setFormView(UrlConstants.HANDLE_DOCUMENT_URL);
		setSuccessView(UrlConstants.HANDLE_DOCUMENT_URL);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Resource resource = null;
		int id = ParamUtil.getInteger(request, "id", 0);
		resource = resourceService.findById(new Long(id));
		if (resource == null) {
			resource = new Resource();
		}
		return resource;
	}

	@Override
	public void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		if (request instanceof MultipartHttpServletRequest) {
			binder.registerCustomEditor(String.class,
					new StringMultipartFileEditor());
		}
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Resource informResource = (Resource) command;
		String loginName = userService.getCurrentLogin(request);
		User user = userService.findByLoginName(loginName);
		if (user != null) {
			String visa = user.getEmployee().getVisa();
			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			Project project = projectService.findByNumber(pnum);
			if (project != null) {
				Date now = new Date();
				String cmd = ParamUtil.getString(request, Constants.CMD, "");
				String fileInfo = ParamUtil.getString(request, "fileInfo", "");
				if (!fileInfo.isEmpty()) {
					String[] f = fileInfo.split(",");
					if (f.length == 2) {
						String rootPath = request.getSession()
								.getServletContext().getRealPath("");
						int index = StringUtils.indexOf(rootPath, "pim");
						rootPath = rootPath.substring(0, index);

						if (Constants.EDIT.equals(cmd)) {
							informResource.setOrignalName(DocumentUtil
									.getFileName(f[0]));
							informResource.setSize(FileUtil
									.getSizeInKByte(rootPath + f[1]));
							informResource.setType(DocumentUtil
									.getFileExtension(f[0]));
							informResource.setPath(f[1]);
							informResource.setLastUpdated(now);
							informResource.setUpdatedBy(visa);
							resourceService.saveOrUpdate(informResource);
							request.setAttribute("editOK", true);

						} else if (Constants.ADD.equals(cmd)) {
							informResource.setAuthor(visa);
							informResource.setCreatedAt(now);
							informResource.setOrignalName(DocumentUtil
									.getFileName(f[0]));
							informResource.setSize(FileUtil
									.getSizeInKByte(rootPath + f[1]));
							informResource.setType(DocumentUtil
									.getFileExtension(f[0]));
							informResource.setPath(f[1]);
							informResource.setSubjectId(project.getProjectid());
							informResource.setSubjectType("Project");
							informResource.setLastUpdated(now);
							informResource.setUpdatedBy(visa);
							resourceService.save(informResource);
							request.setAttribute("addOK", true);

						}
					}
				} else if (Constants.EDIT.equals(cmd)) {
					informResource.setLastUpdated(now);
					informResource.setUpdatedBy(visa);
					resourceService.saveOrUpdate(informResource);
					request.setAttribute("editOK", true);
				}
			}
		}
		return showForm(request, response, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors)
			throws Exception {
		if (userService.isSignedIn(request)) {
			Map<String, Object> bean = new HashMap<String, Object>();
			String loginName = userService.getCurrentLogin(request);
			bean.put("user", userService.findByLoginName(loginName));
			bean.put("isSigned", true);
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));

			int pnum = ParamUtil.getInteger(request, "pnum", 0);
			Project project = projectService.findByNumber(pnum);
			bean.put("project", project);
			bean.put("categories", resourceCategoryService.getAll());

			Object addOK = ParamUtil.getObject(request, "addOK", null);
			Object editOK = ParamUtil.getObject(request, "editOK", null);

			if (addOK != null || editOK != null) {
				response.sendRedirect(UrlConstants.DOCUMENTS_URL
						+ UrlConstants.HTM + "?pnum=" + pnum);
			} else {
				String cmd = ParamUtil.getString(request, Constants.CMD, "");
				bean.put(Constants.CMD, cmd);

				String returnToFullPageURL = ParamUtil.getString(request,
						Constants.RETURN_TO_FULL_PAGE_URL, "");

				if (returnToFullPageURL.isEmpty()) {
					returnToFullPageURL = request.getHeader("referer");
				}
				bean.put(Constants.RETURN_TO_FULL_PAGE_URL, returnToFullPageURL);
			}
			request.setAttribute("bean", bean);
		} else {
			String cmd = ParamUtil.getString(request, Constants.CMD, "");
			String redirectLink = "";
			if (Constants.ADD.equals(cmd)) {
				redirectLink = UrlConstants.HANDLE_DOCUMENT_URL
						+ UrlConstants.HTM;
			} else if (Constants.EDIT.equals(cmd)) {
				int id = ParamUtil.getInteger(request, "id", 0);
				redirectLink = UrlConstants.HANDLE_DOCUMENT_URL
						+ UrlConstants.HTM + "?id=" + id;
			}
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return super.showForm(request, response, errors);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ResourceCategoryService getResourceCategoryService() {
		return resourceCategoryService;
	}

	public void setResourceCategoryService(
			ResourceCategoryService resourceCategoryService) {
		this.resourceCategoryService = resourceCategoryService;
	}

	public ResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public ProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(ProjectService projectService) {
		this.projectService = projectService;
	}

}
